<?php

namespace app\common\model\hfztcy;

use app\common\model\BaseModel;
use app\common\model\service\LibUploadCompressImage;
use common\Common;
use think\Db;
use think\Exception;
use think\Validate;

//公共函数

/**
 * 会员
 * @name LibMember.php
 * @package hfztcy
 * @category model
 * @link http://www.chanekeji.com
 * @author rxy
 * @version 1.0
 * @copyright CHANGE INC
 * @since 2022-06-17
 */
class LibMember extends BaseModel
{
    protected $model;
    protected $table = 'hfztcy_user';

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = db($this->table);
        parent::__construct();
    }

    /**
     * 添加表单信息
     */
    public function addMember($condition)
    {
        try {
            $result = $this->model->insertGetId($condition);
            if (true == $result) {
                return Common::errorArray(0, "添加成功", $result);
            } else {
                return Common::errorArray(1, "添加失败", $result);
            }
        } catch (Exception $ex) {
            $this->errorLog(__CLASS__, __FUNCTION__, $ex);
            return Common::errorArray(1, "数据库操作失败" . $ex->getMessage(), $ex);
        }
    }

    /**
     * Info: 关联微信用户表的用户信息
     * Date: 2022/11/18 8:50
     */
    public function findMemberToUser ($user_id)
    {
        try {
            $sql = <<< SQL
SELECT a.id,a.parent_id,a.nick_name,a.account,a.identity,a.city acity,a.country aarea,a.head_img_url,
       b.user_id,b.username,b.city,b.area,b.balance,b.total_balance,
       b.is_vip,b.is_vip_video,b.is_red_mother_video,b.is_store_video,b.is_disabled,b.is_platform_give,b.vip_open_time
FROM `base_user` AS a 
    LEFT JOIN `hfztcy_user` AS b ON `a`.`id` = `b`.`user_id` 
WHERE `a`.`id` = '{$user_id}'
SQL;
            $reslut = Db::query($sql);
            if ($reslut) {
                return Common::errorArray(0, "查询成功", $reslut[0]);
            } else {
                return Common::errorArray(1, "查询为空", $reslut);
            }
        } catch (Exception $ex) {
            $this->errorLog(__CLASS__, __FUNCTION__, $ex);
            return Common::errorArray(1, "数据库操作失败" . $ex->getMessage(), $ex);
        }
    }


    /**
     * 查询单个表单信息
     * @param $condition
     * @param array $result
     */
    public function findMember($condition = '', $field = '')
    {
        try {
            $reslut = $this->model->where($condition)->field($field)->find();
            if (true == $reslut) {
                return Common::errorArray(0, "查询成功", $reslut);
            } else {
                return Common::errorArray(1, "查询为空", $reslut);
            }
        } catch (Exception $ex) {
            $this->errorLog(__CLASS__, __FUNCTION__, $ex);
            return Common::errorArray(1, "数据库操作失败" . $ex->getMessage(), $ex);
        }
    }

    /**
     * 查询多个表单信息
     * @param $condition
     * @param $limit
     * @param $field
     * @param $sort
     * @param array $result
     */
    public function findAllMember($condition = '', $limit = '', $field = '', $sort = 'add_time desc')
    {
        try {
            $reslut = $this->model->where($condition)->order($sort)->limit($limit)->field($field)->select();
            if (true == $reslut) {
                return Common::errorArray(0, "查询成功", $reslut);
            } else {
                return Common::errorArray(1, "查询为空", $reslut);
            }
        } catch (Exception $ex) {
            $this->errorLog(__CLASS__, __FUNCTION__, $ex);
            return Common::errorArray(1, "数据库操作失败" . $ex->getMessage(), $ex);
        }
    }

    /**
     * 更新表单信息
     * @param $condition
     * @param $userInfo
     * @param array $result
     */
    public function updateMember($condition, $userInfo)
    {
        try {
            $reslut = $this->model->where($condition)->update($userInfo);
            if ($reslut >= 0) {
                return Common::errorArray(0, "更新成功", $reslut);
            } else {
                return Common::errorArray(1, "更新失败", $reslut);
            }
        } catch (Exception $ex) {
            $this->errorLog(__CLASS__, __FUNCTION__, $ex);
            return Common::errorArray(1, "数据库操作失败" . $ex->getMessage(), $ex);
        }
    }

    /**
     * 删除表单信息
     * @param $condition
     * @param array $result
     */
    public function deleteAllMember($ids)
    {
        $condition = array('id' => array('in', $ids));
        try {
            $reslut = $this->model->where($condition)->delete();;
            if (true == $reslut) {
                return Common::errorArray(0, "删除成功", $reslut);
            } else {
                return Common::errorArray(1, "删除失败", $reslut);
            }
        } catch (Exception $ex) {
            $this->errorLog(__CLASS__, __FUNCTION__, $ex);
            return Common::errorArray(1, "数据库操作失败" . $ex->getMessage(), $ex);
        }
    }

    /**
     * 删除表单信息
     * @param $condition
     * @param array $result
     */
    public function deleteMember($ids)
    {
        $condition = array('id' => $ids);
        try {
            $reslut = $this->model->where($condition)->delete();;
            if (true == $reslut) {
                return Common::errorArray(0, "删除成功", $reslut);
            } else {
                return Common::errorArray(1, "删除失败", $reslut);
            }
        } catch (Exception $ex) {
            $this->errorLog(__CLASS__, __FUNCTION__, $ex);
            return Common::errorArray(1, "数据库操作失败" . $ex->getMessage(), $ex);
        }
    }

    /**
     * 字段值加1
     * @param $condition
     * @param string $field
     * @param int $optval
     * @param array $reslut
     */
    public function increaseField($condition, $field, $optval = 1)
    {
        try {
            $reslut = $this->model->where($condition)->setInc($field, $optval);;
            if (true == $reslut) {
                return Common::errorArray(0, "修改成功", $reslut);
            } else {
                return Common::errorArray(1, "修改失败", $reslut);
            }
        } catch (Exception $ex) {
            $this->errorLog(__CLASS__, __FUNCTION__, $ex);
            return Common::errorArray(1, "数据库操作失败" . $ex->getMessage(), $ex);
        }
    }

    /**
     * 字段值减1
     * @param $condition
     * @param string $field
     * @param int $optval
     * @param array $reslut
     */
    public function decreaseField($condition, $field, $optval = 1)
    {
        try {
            $reslut = $this->model->where($condition)->setDec($field, $optval);;
            if (true == $reslut) {
                return Common::errorArray(0, "修改成功", $reslut);
            } else {
                return Common::errorArray(1, "修改失败", $reslut);
            }
        } catch (Exception $ex) {
            $this->errorLog(__CLASS__, __FUNCTION__, $ex);
            return Common::errorArray(1, "数据库操作失败" . $ex->getMessage(), $ex);
        }
    }

    /**
     * Info: 游客
     * Date: 2022/11/10 13:49
     */
    public function pagingGuest ($page, $whereStr)
    {
        $where = 'id IS NOT NULL';
        if ($whereStr) {
            $where = "{$whereStr}";
        }

        $sql = <<< SQL
SELECT a.*
FROM `base_user` `a` 
WHERE {$where} 
ORDER BY a.add_time DESC
SQL;

        return $this->getPagingList($page,$sql);
    }

    /**
     * 红娘团队
     */
    public function pagingRedMotherTeam($page, $whereStr, $sort = 'add_time DESC')
    {
        $where = 'id IS NOT NULL';
        if ($whereStr) {
            $where = "{$whereStr}";
        }

        $sql = <<< SQL
SELECT * 
FROM (
    SELECT c.one_user_id,c.two_user_id,c.id cid,a.id,a.nick_name,a.identity,a.head_img_url,a.parent_id,a.add_time register_time,a.total_balance atotal_balance,a.balance abalance,a.commission acommission,
           b.user_id,b.identity_id,b.username,b.mobile,b.sex,b.age,b.birthday,b.income,b.province,b.city,b.area,
           b.address,b.educate,b.marriage,b.height,b.weight,b.is_children,b.want_children,b.love_content,b.choose_spouse,
           b.hobby,b.add_time,b.balance,b.total_balance,b.commission,b.state,b.photo_list,b.share_num,b.like_num,b.fans_num,b.is_vip,
           b.is_vip_video,b.is_red_mother_video,b.is_store_video,b.is_disabled,b.vip_open_time,b.audit_state,b.audit_msg,b.audit_time
    FROM `hfztcy_member_distribute` `c` 
        LEFT JOIN `base_user` `a` 
            ON `c`.`user_id` = `a`.`id`
        LEFT JOIN `{$this->table}` `b` 
            ON `c`.`user_id`=`b`.`user_id` 
) AS a 
WHERE {$where} 
ORDER BY {$sort} 
SQL;

        return $this->getPagingList($page,$sql);
    }

    /**
     * 会员团队
     */
    public function pagingMemberTeam($page, $whereStr)
    {
        $where = 'id IS NOT NULL';
        if ($whereStr) {
            $where = "{$whereStr}";
        }

        $sql = <<< SQL
SELECT * 
FROM (
    SELECT a.id,a.nick_name,a.identity,a.head_img_url,a.parent_id,a.add_time register_time,a.total_balance atotal_balance,a.balance abalance,a.commission acommission,
           b.user_id,b.identity_id,b.username,b.mobile,b.sex,b.age,b.birthday,b.income,b.province,b.city,b.area,
           b.address,b.educate,b.marriage,b.height,b.weight,b.is_children,b.want_children,b.love_content,b.choose_spouse,
           hobby,b.add_time,b.balance,b.commission,b.total_balance,b.state,b.photo_list,b.share_num,b.like_num,b.fans_num,b.is_vip,
           b.is_vip_video,b.is_red_mother_video,b.is_store_video,b.is_disabled,b.vip_open_time,b.audit_state,b.audit_msg,b.audit_time
    FROM `base_user` `a` 
        LEFT JOIN `{$this->table}` `b` 
            ON `a`.`id`=`b`.`user_id` 
) AS a 
WHERE {$where} 
ORDER BY a.register_time DESC
SQL;

        return $this->getPagingList($page,$sql);
    }

    /**
     * 注册会员
     */
    public function pagingMember($page, $whereStr, $sort = 'add_time')
    {
        $where = 'id IS NOT NULL';
        if ($whereStr) {
            $where = "{$whereStr}";
        }

        $sql = <<< SQL
SELECT * 
FROM (
    SELECT b.id,b.nick_name,b.identity,b.head_img_url,b.parent_id,b.total_balance atotal_balance,b.balance abalance,b.commission acommission,
           a.user_id,a.identity_id,a.username,a.mobile,a.sex,a.age,a.birthday,a.income,a.province,a.city,a.area,a.shape,a.job,
           a.address,a.educate,a.marriage,a.height,a.weight,a.is_children,a.want_children,a.love_content,a.choose_spouse,
           a.hobby,a.add_time,a.balance,a.total_balance,a.commission,a.state,a.photo_list,a.share_num,a.like_num,a.fans_num,a.is_vip,
           a.is_vip_video,a.is_red_mother_video,a.is_store_video,a.is_disabled,a.vip_open_time,a.audit_state,a.audit_msg,a.audit_time,a.register_user_count
    FROM `{$this->table}` `a` 
        INNER JOIN `base_user` `b` ON `a`.`user_id`=`b`.`id` 
) AS a 
WHERE {$where} 
ORDER BY {$sort} DESC
SQL;

        return $this->getPagingList($page,$sql);
    }

    /**
     * Info: 分页
     * Date: 2022/11/14 15:09
     */
    private function getPagingList ($page, $sql)
    {
        $page['pageIndex'] ? $pageIndex = $page['pageIndex'] : $pageIndex = 1;
        $page['pageSize'] ? $pageSize = $page['pageSize'] : $pageSize = 10;

        $m = ($pageIndex - 1) * $pageSize;
        $n = $pageSize;

        $limitSql = $sql . " LIMIT {$m}, {$n}";
        //echo $sql;die();
        $sqlAll = $sql;

        $result['data']['dataList'] = Db::query($limitSql);
        $sql = "SELECT count(count_table.id) as total_record_num  from ( {$sqlAll} ) as count_table";

        $count = Db::query($sql);
        //如果之后1页，手动添加分页信息
        $result['data']['pageInfo']['current_page'] = $pageIndex;
        $result['data']['pageInfo']['first_page'] = 1;
        $result['data']['pageInfo']['prev_page'] = $pageIndex - 1;
        $result['data']['pageInfo']['next_page'] = $pageIndex + 1;
        $result['data']['pageInfo']['last_page'] = ceil($count[0]['total_record_num'] / $pageSize);
        $result['data']['pageInfo']['total_count'] = $count[0]['total_record_num'];
        $result['data']['pageInfo']['total_page'] = ceil($count[0]['total_record_num'] / $pageSize);
        $result['data']['pageInfo']['page_size'] = $pageSize;
        $result['data']['pageInfo']['all_pages'] = ceil($count[0]['total_record_num'] / $pageSize);
        $result['errorCode'] = 0;
        $result['errorInfo'] = '查询成功';

        return $result;
    }

    /**
     * Info: 上传图片
     * Date: 2022/6/17 9:45
     */
    public function uploadMemberIdCardFront()
    {
        $file = request()->file('id_card_front');
        // 移动到框架应用根目录/public/uploads/目录下
        if ($file) {
            $moveImage = $file->move(ROOT_PATH . 'public' . DS . 'upload/image/id_card_front/');
            if ($moveImage) {
                //输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                $name = $moveImage->getSaveName();
                $name = str_replace("\\", "/", $name);
                $new_path = "upload/image/id_card_front/" . $name;
                //$thumbImage = Image::open(ROOT_PATH.'public'.$name)->thumb(100,100)->save($thumb); //上传生成缩略图
                return Common::errorArray(0, "上传成功", ['path' => $new_path]);
            } else {
                // 上传失败获取错误信息
                return Common::errorArray(1, "上传失败", $file->getError());
            }
        } else {
            return Common::errorArray(2, "没有上传", false);
        }
    }

    /**
     * Info: 上传图片
     * Date: 2022/6/17 9:45
     */
    public function uploadMemberIdCardReverse()
    {
        $file = request()->file('id_card_reverse');
        // 移动到框架应用根目录/public/uploads/目录下
        if ($file) {
            $moveImage = $file->move(ROOT_PATH . 'public' . DS . 'upload/image/id_card_reverse/');
            if ($moveImage) {
                //输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                $name = $moveImage->getSaveName();
                $name = str_replace("\\", "/", $name);
                $new_path = "upload/image/id_card_reverse/" . $name;
                //$thumbImage = Image::open(ROOT_PATH.'public'.$name)->thumb(100,100)->save($thumb); //上传生成缩略图
                return Common::errorArray(0, "上传成功", ['path' => $new_path]);
            } else {
                // 上传失败获取错误信息
                return Common::errorArray(1, "上传失败", $file->getError());
            }
        } else {
            return Common::errorArray(2, "没有上传", false);
        }
    }

    /**
     * Info: 会员编号
     * Date: 2022/6/28 10:49
     */
    public function generateMemberID()
    {
        $order_num = substr(date('Y',time()),-2) . substr(time(),-4);
        $orderInfo = $this->findMember(array('identity_id' => $order_num));
        if ($orderInfo['errorCode'] == 0) {
            $this->generateMemberID();
        } else {
            return $order_num;
        }
    }

    /**
     * Info: 数据验证
     * Date: 2022/6/17 9:55
     */
    public function goCheck($data, $opt = 'add')
    {
        $rule = [
            'user_id' => 'require',
            'username' => 'require|max:50',
            'mobile' => 'require',
            'sex' => 'require',
            'age' => 'require',
            'birthday' => 'require',
            'address' => 'require',
        ];

        $msg = [
            'user_id.require' => '用户不能为空',
            'username.require' => '姓名不能为空',
            'mobile.require' => '手机号不能为空',
            'sex.require' => '性别不能为空',
            'age.require' => '年龄不能为空',
            'birthday.require' => '生日不能为空',
            'address.require' => '详细地址不能为空',
        ];

        $scene = [
            'add' => [
                'user_id',
                'username',
                'mobile',
                'sex',
                'age',
                'birthday',
                'address',
            ],
            'edit' => [
                'user_id',
                'username',
                'mobile',
                'sex',
                'age',
                'birthday',
                'address',
            ],
            'photo' => [
                'user_id',
                'photo_list',
            ],
        ];

        $validate = new Validate($rule, $msg);
        $validate->scene($opt, $scene[$opt]);
        if (!$validate->scene($opt)->check($data)) {
            return Common::errorArray(1, $validate->getError(), false);
        }
        return Common::errorArray(0, '验证通过', true);
    }

    /**
     * Info: 更新会员状态
     * Date: 2022/11/21 9:31
     */
    public function updateMemberState ($user_id)
    {

        $sql = <<< SQL
SELECT identity FROM `base_user` WHERE `id` = {$user_id}
SQL;
        $userRes = Db::query($sql);
        $identity = [];
        if ($userRes) {
            $identity = explode(',',$userRes[0]['identity']);
        }
        $identity = array_map('intval',$identity);
        //移除vip会员身份
        $identity = array_map(function ($val) use ($identity) {
            if ($val == 2) {
                unset($identity[$val]);
            } else {
                return $val;
            }
        },$identity);
        //重置为普通用户
        if (empty($identity)) array_push($identity,1);
        $identity = array_filter($identity);
        $identity = array_unique($identity);
        if (empty($identity)) array_push($identity,1);
        if ($identity) {
            $identityStr = implode(',',$identity);
            $sql = <<< SQL
UPDATE base_user 
SET identity='{$identityStr}' 
WHERE `id` = '{$user_id}'
SQL;
            Db::execute($sql);

            $sql = <<< SQL
UPDATE hfztcy_user 
SET is_vip=0,state='{$identityStr}' 
WHERE `user_id` = '{$user_id}'
SQL;
            Db::execute($sql);
        }
    }

    /**
     * Info: 上传图片
     * Date: 2022/6/17 9:45
     */
    public function uploadMemberPhoto()
    {
//        $file = request()->file('file');
//        // 移动到框架应用根目录/public/uploads/目录下
//        if ($file) {
//            $dir = "upload/member/photos/";
//            $moveImage = $file->move(ROOT_PATH . 'public' . DS . $dir);
//            if ($moveImage) {
//                $name = $moveImage->getSaveName();
//                $name = str_replace("\\", "/", $name);
//                $new_path = $dir . $name;
//                return Common::errorArray(0, "上传成功", ['path' => $new_path]);
//            } else {
//                // 上传失败获取错误信息
//                return Common::errorArray(1, "上传失败", $file->getError());
//            }
//        } else {
//            return Common::errorArray(2, "没有上传", false);
//        }
        $res = (new LibUploadCompressImage('member/photos'))->uploadImage();
        if ($res['errorCode'] == 0) {
            return Common::errorArray(0, "上传成功", ['path' => $res['data']]);
        }
        return $res;
    }

    /**
     * Info: 上传视频封面
     * Date: 2022/6/17 9:45
     */
    public function uploadVcrImgs()
    {
//        $file = request()->file('imgs');
//        if ($file) {
//            $dir = "upload/member/video_cover/";
//            $moveImage = $file->move(ROOT_PATH . 'public' . DS . $dir);
//            if ($moveImage) {
//                $name = $moveImage->getSaveName();
//                $name = str_replace("\\", "/", $name);
//                $new_path = $dir . $name;
//                return Common::errorArray(0, "上传成功", ['path' => $new_path]);
//            } else {
//                // 上传失败获取错误信息
//                return Common::errorArray(1, "上传失败", $file->getError());
//            }
//        } else {
//            return Common::errorArray(2, "没有上传", false);
//        }
        $res = (new LibUploadCompressImage('member/video_cover','imgs'))->setUserOriginalName()->uploadImage();
        if ($res['errorCode'] == 0) {
            return Common::errorArray(0, "上传成功", ['path' => $res['data']]);
        }
        return $res;
    }
}

?>